package com.hserver.docker.controller;

import cn.hserver.plugin.web.annotation.Controller;
import cn.hserver.plugin.web.annotation.GET;
import cn.hserver.plugin.web.annotation.POST;
import cn.hserver.plugin.web.interfaces.HttpResponse;
import com.hserver.docker.bean.DockerUrl;
import com.hserver.docker.config.ConstConfig;
import com.hserver.docker.service.DockerService;
import com.hserver.docker.service.DockerUrlService;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.server.util.JsonResult;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hxm
 */
@Controller("/dockerUrl/")
public class DockerUrlController {

    @Autowired
    private DockerService dockerService;

    @Autowired
    private DockerUrlService dockerUrlService;


    @GET("dockerUrl")
    public void dockerUrl(HttpResponse response) {
        Map<String, Object> data = new HashMap<>(1);
        data.put("dockerUrl", ConstConfig.DOCKER_URL);
        data.put("dockerList", dockerUrlService.list());
        response.sendTemplate("docker/dockerUrl.ftl", data);
    }

    @GET("addDockerUrl")
    public void index(HttpResponse response) {
        response.sendTemplate("/docker/addDockerUrl.ftl");
    }

    @POST("addDockerUrl")
    public JsonResult addDockerUrl(String name, String url) {
        if (url != null && url.trim().length() > 0 && name != null && name.trim().length() > 0) {
            Boolean aBoolean = dockerService.checkDockerUrl(url);
            if (aBoolean) {
                dockerUrlService.add(name, url);
                return JsonResult.ok("设置完成");
            } else {
                return JsonResult.error("哎呀，地址有问题哦！");
            }
        }
        return JsonResult.error("参数不能为空");
    }

    @POST("change")
    public JsonResult change(String id, Integer type) {
        if (type == 1) {
            dockerUrlService.remove(id);
        } else {
            DockerUrl byId = dockerUrlService.getById(id);
            Boolean aBoolean = dockerService.checkDockerUrl(byId.getUrl());
            if (aBoolean) {
                ConstConfig.DOCKER_URL=byId.getUrl();
                return JsonResult.ok("设置完成");
            } else {
                return JsonResult.error("哎呀，地址有问题哦！");
            }
        }
        return JsonResult.ok();
    }
}
